<?php
require_once(MODX_MANAGER_PATH.'../assets/plugins/dataFrolic/tmplvars2.inc.php'); //for rendering database fields
require_once(MODX_MANAGER_PATH.'includes/tmplvars.commands.inc.php');

global $replace_richtexteditor;


//TODO: support multiple image uploaders per page
//$field_prefix is usually the form action (CRUD)
function df_make_form($table_info, $current_doc_id, $form_prefix='', $current_record_id='', $plugin_cell = ''){
	global $modx, $which_editor;

	$table = $table_info->getTableName();
	$foreign_keys = $table_info->getForeignKeys();
	$primary_key = $table_info->getPrimaryKey();
	
	// echo "table: $table, current record: $current_record_id, foreign keys: $foreign_keys";
	
	if ($current_record_id != ''){
		$resource = $modx->db->select('*',$table, $table_info->getPrimaryKey().'='.$current_record_id);
		$this_record = $modx->db->getRow($resource);
	}else{
		$resource = $modx->db->select('*',$table);
	}

		
	echo "<!-- begin df_make_form -->";
	$fields = $modx->db->getTableMetaData($table);
	
	
	// $schma_name = mysql_query("SELECT DATABASE()");
	// $field_comments = $modx->db->query("SELECT COLUMN_COMMENT FROM COLUMNS WHERE TABLE_SCHEMA = '$schma_name' AND TABLE_NAME = '$table'");
	
	
	
	$i = 0;
	foreach ($fields as $field){
		$field_comment = $modx->db->getRow($field_comments, 'num');
		$field_comment = $field_comment[0];
		
		$fieldName = $field['Field']; //could also use mysql_field_name($resource,$i)
	
		if (strlen($primary_key) > 0 && $primary_key == $fieldName){
			$i++;
			continue; // could also check for auto increment here..
		}
	
		echo "\t\t",'<tr><td colspan="2"><div class="split"></div></td></tr>',"\n"; //splitter row
		
		//  our special case for referencing another table:
		// (this is practically extending the tmpvar.inc.php).  note that we don't care about label name for now.
		if (df_is_document_field($fieldName, $foreign_keys)){

			//disabled if foreign key is for this page's parent!:
			// echo "<label for='df_$fieldName'>".ucwords($fieldName).": </label>\n
			$o = "<select name='$form_prefix_$fieldName' id='$form_prefix_$fieldName' ";
			//chop off the id and see if it matched the current 
			// reset($foreign_keys);  //first foreign key is the one we want
			//todo: standardized convention for parent resource

			//select values from db:
			$parent_options = $modx->db->select('id, pagetitle','modx_site_content','parent='.$foreign_keys[$fieldName]);
			$oo = '';
			$disabled = false;
			while( $parent_option = $modx->db->getRow($parent_options) ){
				// echo $office['name'];
				$oo .= "\n\t<option value='$parent_option[id]'";
				if ($parent_option['id'] == $current_doc_id){
					$oo .= ' selected';
					$disabled = true;
				}
				// $o .= ($parent_option['id'] == $current_doc_id) ? ' selected>' : '>';
				$oo .= "> $parent_option[pagetitle] ($parent_option[id])</option>";
			}
			$o .= ($disabled) ? ' disabled=disabled>' : '>';
			$o .= $oo; 
			$o .= "\n</select>";
			
			$name = mysql_field_name($resource,$i);
			if ($name == "LOB_id") {
				 $name = "Line of Business";
			}
			//TODO: could set description to column comment here!!
			renderFormRow($name,$field_comment,$o);
			
		}elseif ($fieldName == "image"){
			$val = isset($this_record) ? $this_record[$fieldName] : '';
			
			echo "<tr><td colspan='2'>";
			echo '<span id="uploaded_img_display">'.$val.'</span>';
			echo '<input type="hidden" id="uploaded_img_field" name="df_image" value="">';  //putting val here would make problems...
			echo '<button id="upload_img_btn" onclick="launch_img_uploader();return false;">Add/Change Image</button>';
			echo "</tr></td>";
			
		}elseif($fieldName == "attachments"){
			$val = isset($this_record) ? $this_record[$fieldName] : '';
			echo "<tr><td colspan='2'>";
			echo '<span id="attachments_display">';
				if (isset($this_record)) {
					$entries = explode(',', $val);
					echo "<strong>Attachment paths:</strong>";
					foreach ($entries as $attachment){
						echo '<br><em>http://www.swett.com/assets/news/'.rawurlencode($attachment).'</em><br>';
					}
				};
			echo '</span>';
			echo '<input type="hidden" id="attachments_field" name="df_attachments" value="'.$val.'">';
			echo '<button id="upload_attachment_btn" onclick="launch_attachment_uploader();return false;">Add Attchment</button>';
			echo "</tr></td>";
			
		}else{	
			//renderFormElement($field_type, $field_id, $default_text, $field_elements, $field_value, $field_style='')
			/* this (^^) is used for rendering TV fields.  As such, various conversions and assumptions must be made,
			in order to turn the field types in the db in to guesses as what the field should be. 
			$field_type, possible values (redundant omitted):
				text,textareamini,richtext/textarea,date,dropdown,listbox,listbox-multiple,checkbox,option,image,file
			$field_id: postfix value for name and id attributes of the input elements
			$default_text: used to fill the field when no field value supplied
			field_elements: input option values
			field_value: current value
			field_style: complete tag (technically could be any), optional.  can be used for setting clss for validation..!
			*/

			$type = mysql_field_type($resource,$i);
			$len = intval(mysql_field_len($resource,$i));
			// **************NOTE: the following code fixes field length for varchar, which is tripled from charset
			// it may be possible this 'bug?' would be fixed in upgrading, breaking this script.
			// http://bugs.mysql.com/bug.php?id=28820
			if ($type == 'string') $len = $len/3;

		
			$default = $field['Default'];

			$initial_value = (isset($this_record)) ? stripslashes($this_record[$fieldName]) : '';
			
			$field_elements = '';
			if ( df_is_foreign_field($fieldName, $foreign_keys) ){ //foreign key for another table
				$field_elements = "@SELECT title, id FROM ".$foreign_keys[$fieldName]->getTableName(); //we know obj not str because of condition above
				$input_type = 'dropdown';
				$validation = '';
			}else{
				$input_type = guess_input_type($type, $len, 'tv'.$form_prefix.'_'.$fieldName);
				$validation = guess_input_validation($field, $type, $len);
			}

			$element = renderFormElement2($input_type, $form_prefix.'_'.$fieldName, $default, $field_elements, $initial_value, "style='$validation'");

			
			$field_name = mysql_field_name($resource,$i);
			
			// quick kludge comment:
			// should be using database column comment..
			if ($field_name == "status"){ $field_comment = "Active?";}  
			

			//TODO: could set description to column comment here
			//todo: use summary fields here instead when applicable
			renderFormRow($field_name,$field_comment,$element);

			// echo renderFormElement($input_type, $fieldName, $default, 'something about @ bindings', $this_record[$fieldName], "style='$validation'");


			

			
		} //end conditional field selector
		$i++;
	} //end fields loop
	
	echo "<input type='hidden' name='df_table' value='$table'>";
	echo "<input type='hidden' name='df_id' value='$current_record_id'>";
	echo "<input type='hidden' name='table_info' value='".urlencode(serialize($table_info))."'>";
	echo "<input type='hidden' name='plugin_cell' value='".$plugin_cell."'>";

	global $replace_richtexteditor;
	//make the textareas become editors
	if (is_array($replace_richtexteditor)) {
		$evtOut = $modx->invokeEvent('OnRichTextEditorInit', array(
			'modx' => &$modx,
			'editor' => $which_editor,
			'elements' => $replace_richtexteditor
		));

	}

} //end df_make_form


function renderFormRow($caption, $description, $element){
	echo "\t\t",'<tr style="height: 24px;"><td align="left" valign="top" width="150"><span class="warning">',$caption,"</span>\n",
	     "\t\t\t",'<br /><span class="comment">',$description,"</span></td>\n",
	     "\t\t\t",'<td valign="top" style="position:relative">',"\n",
	     "\t\t\t",$element,"\n";
	     "\t\t</td></tr>\n";
}

//$field_type, possible values (redundant omitted):
//	text,textareamini,richtext/textarea,date,dropdown,listbox,listbox-multiple,checkbox,option,image,file
function guess_input_type($type, $len, $name){
	global $replace_richtexteditor;
	//possible insert here - some kind of lookup table?
	
	// for now, simple converstions
	// one intelligent bit: if length is large, call it a textarea
	// also, if int, size == 2, call it a chckbox
	// if ($name == 'tvnew_image') return "image";
	
	//TODO: add date
	switch ($type){
		case 'int':
			if ($len > 2){return 'text';}else{return 'checkbox';}
		case 'string':			
			if ($len > 300){
				// add this field as RTeditor
				if (is_array($replace_richtexteditor)) {
					$replace_richtexteditor = array_merge($replace_richtexteditor, array("$name"));
				} else {
					$replace_richtexteditor = array("$name");
				}
				return 'textarea';
			}
			
			if ($len > 100){return 'textareamini';}
			
			return 'text';
		case 'date':
			return 'date';
		case 'datetime':
			return 'datetime';
		}
		
}

// guesses 
//todo: complete validation OCD: numbers, length, characters, etcetc
function guess_input_validation($field, $type, $len){
	//first guesses from field type (not null, varchar, int, etc)
	$o = 'width:300px;';
	
	if (!($field['Null'] == "YES")){
		$o .= ' required';
	}
	
	if($type == 'int'){ $o .= ' integer';}
	
	$o .= "maxlength($len)";
	
	return $o;
}


?>